/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao.generic;
import java.util.List;
import org.hibernate.Query;
import mapeo.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 *
 * @author Elias Mendoza
 */

public class GenericDAO {
  protected Session sesion;
    protected Transaction tx;

    public <Registro,Key> Key guardar(Registro r) throws HibernateException {
        Key id = null;
        try {
            iniciarOperacion();
            sesion.save(r);
            tx.commit();
        } catch (HibernateException he) {
            manejarExcepcion(he);
            throw he;
        } finally {
            sesion.close();
        }

        return id;
    }
    public <Registro> void actualizar(Registro r) throws HibernateException {
        try {
            iniciarOperacion();
            sesion.update(r);
            tx.commit();
        } catch (HibernateException he) {
            manejarExcepcion(he);
            throw he;
        } finally {
            sesion.close();
        }
    }

    public <Registro> void eliminar(Registro r) throws HibernateException {
        try {
            iniciarOperacion();
            sesion.delete(r);
            tx.commit();
        } catch (HibernateException he) {
            manejarExcepcion(he);
            throw he;
        } finally {
            sesion.close();
        }
    }

  protected void iniciarOperacion() throws HibernateException {
    sesion = HibernateUtil.getSessionFactory().openSession();
    tx = sesion.beginTransaction();
  }

  protected void manejarExcepcion(HibernateException he) throws HibernateException {
    tx.rollback();
    throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he);
  }
  
}
